/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package ru.ssau.utils;

import java.util.Date;
import javax.jms.*;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import logging.EntityLoggerBean;


public class JMSUtil {

    private JMSUtil() {

    }

    public static Queue getLogMessageQueue() throws NamingException {
        Context ctx = new InitialContext();
        Queue queue = (Queue) ctx.lookup("jms/logQueue");
        ctx.close();
        return queue;
    }

    public static QueueConnectionFactory getQueueConnectionFactory() throws NamingException {
        Context ctx = new InitialContext();
        QueueConnectionFactory factory = (QueueConnectionFactory) ctx.lookup("jms/queueConnFactory");
        ctx.close();
        return factory;
    }

    public static QueueConnection getQueueConnection() throws NamingException, JMSException {
        return getQueueConnectionFactory().createQueueConnection();
    }

    public static void closeConnection(QueueSender sender, javax.jms.Session session, Connection connection) {
        if(sender != null) {
            try {
                sender.close();
            } catch(JMSException ex) {
            }
        }
        
        if(session != null) {
            try {
                session.close();
            } catch(JMSException ex) {
            }
        }

        if(connection != null) {
            try {
                connection.close();
            } catch (JMSException ex) {
            }
        }        
    }

    public static void sendLogMessage(String entityName, int entityId, Date changeDate, String action) {
        QueueConnection conn = null;
        QueueSession session = null;
        QueueSender sender = null;
        try {
            conn = JMSUtil.getQueueConnection();
            session = conn.createQueueSession(true, 42);
            MapMessage message = session.createMapMessage();
            message.setInt(EntityLoggerBean.ENTITY_ID, entityId);
            message.setString(EntityLoggerBean.ENTITY_NAME, entityName);
            message.setLong(EntityLoggerBean.CHANGE_TIME, changeDate.getTime());
            message.setString(EntityLoggerBean.PERFORMED_ACTION, action);
            sender = session.createSender(JMSUtil.getLogMessageQueue());
            sender.send(message);
        } catch(NamingException e) {
            e.printStackTrace();
        } catch(JMSException e) {
            e.printStackTrace();
        } finally {
            JMSUtil.closeConnection(sender, session, conn);
        }
    }

}
